package com.qf.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
@WebServlet("/cookie")
public class CookieServlet  extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String encode = URLEncoder.encode("2206班级", "utf-8");

        Cookie cookie = new Cookie("cookie_2206", encode);
        //设置哪些路径下可以获取该cookie   / 该域下的任意路径都可以获取
        cookie.setPath("/");
        // 设置域名(本质上是一个ip)
        cookie.setDomain("localhost");
        //设置生存时间
        cookie.setMaxAge(100);

        //添加cookie到相应对象中
        resp.addCookie(cookie);
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().println("访问cookie成功");
    }
}
